﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.User
{
    /// <summary>CCPSIP_036：User 設定個人圖片(大頭照) API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// 檔案 = 個人圖片檔案，格式為 "image/jpeg"，大小須介於 2KB ~ 2MB 之間。

    public class icon_set : IHttpHandler
    {
        private string kIconDirRoot = ChrisKit.RootDir + "CCPSIP\\UserIcon"; //ios.ccp
        private string kIconDirLatest = ChrisKit.RootDir + "CCPSIP\\UserIcon\\Latest"; //ios.ccp


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】檢查上傳檔案
                //
                if (req.Files.Count < 1)
                {
                    throw new Exception("Error_02: No Upload File");//沒有上傳檔案
                }

                int iconSize = req.Files[0].ContentLength;

                if (iconSize < 2 * 1024)
                {
                    throw new Exception("Error_03: The file is too small");//檔案太小
                }
                else if (iconSize > 2 * 1048576)
                {
                    throw new Exception("Error_03: The file is too large");//檔案太大
                }


                //【03】組合檔名
                //
                string logIconDir = string.Format(@"{0}\{1}", kIconDirRoot, userInfo.SIP_Num);
                if (!Directory.Exists(logIconDir))
                {
                    Directory.CreateDirectory(logIconDir);
                }

                string logIconBase = string.Format(@"{0}\{1}_{2:yyyyMMdd}", logIconDir, userInfo.SIP_Num, reqTime);
                string logIconPath = string.Format("{0}.jpg", logIconBase);
                string latestIconPath = string.Format(@"{0}\{1}.jpg", kIconDirLatest, userInfo.SIP_Num);

                if (File.Exists(logIconPath))
                {
                    for (int i = 2; i <= 99; i++)
                    {
                        logIconPath = string.Format("{0}_{1}.jpg", logIconBase, i);
                        if (!File.Exists(logIconPath))
                            break;
                    }
                }

                if (File.Exists(logIconPath))
                {
                    throw new Exception("Error_04: Upload too many times, please try again tomorrow");//單日上傳太多次
                }


                //【04】儲存檔案
                //
                req.Files[0].SaveAs(logIconPath);
                File.Copy(logIconPath, latestIconPath, true);


                //【05】記錄個人圖片更新時間
                //
                OracleKitUser.UpdateIconTime(userInfo.SIP_Num, reqTime, iconSize);


                //【99】回傳結果
                //
                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
